﻿using Eps.Ai.Common;
using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.Forms;
using InfonavaEye.Forms.orderForms;
using InfonavaEye.handler;
using InfonavaEye.Handler;
using InfonavaEye.model;
using InfonavaEye.Service;
using Sylan.Common.Util;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InfonavaEye
{
    public partial class CaptureResultForm : Form
    {

        int currentRowIndex = 0;

        public event Action clearListDelegate;

        public BoxModel boxModel;

        private IReportService reportService = ReportServiceFactory.getService();

        public event Action ListCloseDelegate;

        public CaptureResultForm()
        {
            InitializeComponent();
            this.KeyPreview = true;//让界面能够捕捉到键盘事件
            //Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
        }

        private void ListForm_Load(object sender, EventArgs e)
        {
            previewPanel.Height = (int)(previewPanel.Width * 2048 / 3072);
            previewPanel.Refresh();

            //FormDataBridge.receiveOCRResult += receiveOCRResult;//!!!这里不再用添加的方式，而是用下面的updateResultDelegate来更新
            FormDataBridge.removeResultDelegate += FormDataBridge_removeResultDelegate;
            FormDataBridge.updateResultDelegate += FormDataBridge_updateResultDelegate;
            FormDataBridge.reStraightenDelegate += FormDataBridge_reStraightenDelegate;
            FormDataBridge.redoDelegate += FormDataBridge_redoDelegate;
            //仅在DEBUG模式下才显示拉直图
            if (Config.ALGORITHM_MODE.Equals("DEBUG"))
            {
                panelStraighten.Visible = true;
            }
            this.renderList();
        }

        private void ListForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //FormDataBridge.receiveOCRResult -= receiveOCRResult;//!!!这里不再用添加的方式，而是用下面的updateResultDelegate来更新
            FormDataBridge.removeResultDelegate -= FormDataBridge_removeResultDelegate;
            FormDataBridge.updateResultDelegate -= FormDataBridge_updateResultDelegate;
            FormDataBridge.reStraightenDelegate -= FormDataBridge_reStraightenDelegate;
            FormDataBridge.redoDelegate -= FormDataBridge_redoDelegate;
            if (ListCloseDelegate != null)
            {
                ListCloseDelegate.Invoke();
            }
        }

        private void renderList()
        {
            FormDataBridge.OCRDataList.Sort((a, b) =>
            {
                if (a.rowNum < b.rowNum)
                {
                    return -1;
                }
                return 1;
            });

            DataGridViewRow[] rows = new DataGridViewRow[FormDataBridge.OCRDataList.Count];
            int i = 0;
            foreach (OCRResult result in FormDataBridge.OCRDataList)
            {
                var finalResult = ParseFinalResult(result.code);

                //result.rowNum.ToString(), result.code, finalResult, locationStr
                //dataGridView.Rows.Add(new object[] { false, });//向控件中添加数据

                DataGridViewRow row = new DataGridViewRow();
                row.MinimumHeight = 45;
                row.Cells.AddRange(new DataGridViewCell[]{
                    new DataGridViewCheckBoxCell() {
                        Value = false,
                    },
                    new DataGridViewTextBoxCell() {
                        Value=result.rowNum,
                    },
                   
                  /*  new DataGridViewImageCell()
                    {
                        Value =  Image.FromFile(result.filePath),
                        ImageLayout = DataGridViewImageCellLayout.Zoom,
                    },*/
                    new DataGridViewTextBoxCell() {
                        Value=result.code,
                    },
                      new DataGridViewTextBoxCell() {
                        Value=formatNailLocation(result),
                    },
                      new DataGridViewTextBoxCell() {
                        Value=result.errorMsg,
                    },
                });
                rows[i] = row;
                i++;
            }
            dataGridView.Rows.AddRange(rows);

            if (FormDataBridge.OCRDataList.Count > 0)
            {
                this.dataGridView.CurrentCell = this.dataGridView.Rows[FormDataBridge.OCRDataList.Count - 1].Cells[0];
                CurrentRowChanged(FormDataBridge.OCRDataList.Count - 1);
            }

        }

        private string formatNailLocation(OCRResult result)
        {
            string locationStr = "";
            if (result.nail != null && result.nail.point != null)
            {
                var rowTitle = (result.nail.area.columnTitle!=null && result.nail.area.columnTitle.Length>0 && result.nail.area.columnTitle.Length>result.nail.point.X) ? result.nail.area.columnTitle[result.nail.point.X] : "";
                locationStr = String.Format("{0} 》{1}({2},{3})", result.nail.area.name, rowTitle, result.nail.point.X + 1, result.nail.point.Y + 1);
            }
            return locationStr;
        }

        /// <summary>
        /// 重写ProcessDialogKey，来允许监听方向键
        /// </summary>
        /// <param name="keycode"></param>
        /// <returns></returns>
        protected override bool ProcessDialogKey(Keys keycode)
        {
            Console.WriteLine(keycode);
            return false;

            /* switch (keycode)
             {
                 case Keys.Left:
                 case Keys.Up:
                 case Keys.Right:
                 case Keys.Down:
                     return false;
             }*/
            return true;
        }

        private void FormDataBridge_redoDelegate(OCRResult result)
        {
            if (IsDisposed || !this.IsHandleCreated) return;

            this.BeginInvoke(new Action(() =>
            {
                btnRedo.Text = "重新处理";
                this.btnRedo.Enabled = true;
                CurrentRowChanged(currentRowIndex);
                AutoCloseMessageBox.Show("重新处理成功", "提示");
            }));
        }

        private void FormDataBridge_reStraightenDelegate(OCRResult result)
        {
            if (IsDisposed || !this.IsHandleCreated)
            {
                Console.WriteLine("FormDataBridge_reStraightenDelegate IsDisposed");
                return;
            }

            this.BeginInvoke(new Action(() =>
            {
                btnReStraighten.Text = "重新拉直";
                this.btnReStraighten.Enabled = true;
                CurrentRowChanged(currentRowIndex);
                AutoCloseMessageBox.Show("再次拉直成功", "提示");
            }));
        }

        private void FormDataBridge_removeResultDelegate(OCRResult result)
        {
            if (IsDisposed || !this.IsHandleCreated) return;

            this.BeginInvoke(new Action(() =>
            {
                try
                {
                    for (var i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        int rowNum = int.Parse(dataGridView.Rows[i].Cells[1].Value.ToString());
                        if (rowNum == result.rowNum)
                        {
                            dataGridView.Rows.RemoveAt(i);
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("识别列表删除结果发生异常，异常：{0},详细信息：{1}", ex.Message, ex.StackTrace);
                }
            }));
        }

        private void FormDataBridge_updateResultDelegate(OCRResult result)
        {
            if (IsDisposed || !this.IsHandleCreated) return;

            this.BeginInvoke(new Action(() =>
            {
                try
                {
                    bool findResult = false;
                    //dataGridView.Rows.RemoveAt(result.rowNum - 1);
                    for (int i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        int rowNum = int.Parse(dataGridView.Rows[i].Cells[1].Value.ToString());
                        if (rowNum == result.rowNum)
                        {
                            findResult = true;
                            dataGridView.Rows[i].Cells[2].Value = result.code;
                            dataGridView.Rows[i].Cells[4].Value = result.errorMsg;
                            //dataGridView.Rows[i].Cells[3].Value = ParseFinalResult(result.code);
                            if (previewPanel.Tag.ToString().Equals(result.filePath))
                            {
                                txtCode.Text = result.code;
                                try
                                {
                                    int rowIndex = this.dataGridView.CurrentCell.RowIndex;
                                    CurrentRowChanged(rowIndex);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("显示拉直图时发生异常,文件：{0}，异常：{1},详细信息：{2}", result.straightFilePath, ex.Message, ex.StackTrace);
                                }
                            }
                            if (result.status==2) {
                                CurrentRowChanged(this.dataGridView.CurrentCell.RowIndex);
                            }
                            break;
                        }
                    }

                    if (!findResult) {
                        receiveOCRResult(result);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("识别列表更新结果发生异常，异常：{0},详细信息：{1}", ex.Message, ex.StackTrace);
                }
            }));
        }

        private void receiveOCRResult(OCRResult result)
        {
            if (IsDisposed || !this.IsHandleCreated) return;

            this.BeginInvoke(new Action(() =>
            {
                try
                {
                    //检查是否有重复的，不要重复
                    if (dataGridView.Rows.Count > 0)
                    {
                        int rowNum = int.Parse(dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1].Value.ToString());
                        if (rowNum == result.rowNum)
                        {
                            return;
                        }
                    }

                    var finalResult = ParseFinalResult(result.code);
                    dataGridView.Rows.Add(new Object[] { false, result.rowNum.ToString(), result.code, formatNailLocation(result), result.errorMsg });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("识别列表增加结果发生异常，异常：{0},详细信息：{1}", ex.Message, ex.StackTrace);
                }
            }));
        }

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //点击的是标题栏
            if (e.RowIndex == -1)
            {
                return;
            }

            //点击是每列的行首的数字
            if (e.ColumnIndex == -1)
            {
                int rowIndex = e.RowIndex;
                CurrentRowChanged(rowIndex);
                return;
            }

            string action = dataGridView.Columns[e.ColumnIndex].Name;
            if (action.Equals("delete"))
            {
                if (MessageBox.Show("确定删除吗？", "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    dataGridView.Rows.RemoveAt(e.RowIndex);
                    FormDataBridge.removeAt(e.RowIndex);
                    this.resetRightArea();
                }
            }
            else if (action.Equals("chk"))
            {
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView.Rows[e.RowIndex].Cells["chk"];
                Boolean flag = Convert.ToBoolean(checkCell.Value);
                checkCell.Value = !flag;
            }
            else
            {
                int rowIndex = e.RowIndex;
                CurrentRowChanged(rowIndex);
            }
        }

        private string ParseFinalResult(string code)
        {
            if (!string.IsNullOrEmpty(code))
            {
                Regex regExp = new Regex(@"DB[\s\-]+(\w+)");
                Match match = regExp.Match(code);
                if (match.Groups.Count > 0)
                {
                    return match.Groups[0].Value;
                }
            }
            return code;
        }

        private void CurrentRowChanged(int rowIndex)
        {
            this.BeginInvoke(new Action(() =>
            {
                try
                {
                    if (rowIndex > -1 && FormDataBridge.OCRDataList.Count >= rowIndex + 1)
                    {
                        currentRowIndex = rowIndex;

                        OCRResult result = FormDataBridge.OCRDataList[rowIndex];
                        /*if (previewPanel.BackgroundImage != null) {
                            previewPanel.BackgroundImage.Dispose();
                        }*/
                        previewPanel.BackgroundImage = Image.FromFile(result.filePath);
                        previewPanel.Tag = result.filePath;

                        btnLocation.Visible = result.nail != null;
                        //显示拉直图
                        if (!string.IsNullOrEmpty(result.straightFilePath))
                        {
                            lblStraighten.Visible = true;
                            straightenPictureBox.Visible = true;
                            btnRotate.Visible = true;
                            btnReStraighten.Visible = true;

                           /* if (result.straightFilePath.EndsWith(".jpg"))
                            {
                                straightenPictureBox.Load(result.straightFilePath);
                                btnRotate_Click(null, null);
                            }*/

                            //
                            straightenPictureBox.Load(result.straightFilePath);
                            btnRotate_Click(null, null);
                        }
                        else
                        {
                            lblStraighten.Visible = false;
                            straightenPictureBox.Visible = false;
                            btnRotate.Visible = false;
                            btnReStraighten.Visible = false;
                            if (straightenPictureBox.Image != null)
                            {
                                Graphics g = Graphics.FromImage(straightenPictureBox.Image);
                                g.Clear(Color.White);
                                g.Dispose();
                                straightenPictureBox.Refresh();
                            }
                        }
                        txtCode.Text = result.code;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("识别列表切换行发生异常，异常：{0},详细信息：{1}", ex.Message, ex.StackTrace);
                }
            }));
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                var code = txtCode.Text;
                btnEdit.Enabled = false;
                btnEdit.Text = "修改中";
                if (!string.IsNullOrEmpty(code))
                {
                    int rowNum = int.Parse(dataGridView.Rows[currentRowIndex].Cells[1].Value.ToString());
                    //更改数据源的值
                    FormDataBridge.UpdateItemCode(rowNum, code);
                    //更改单元格的值
                    for (int i = 0, count = dataGridView.ColumnCount; i < count; i++)
                    {
                        if (dataGridView.Columns[i].Name.Equals("code"))
                        {
                            DataGridViewCell aa = dataGridView.Rows[currentRowIndex].Cells[i];
                            aa.Value = code;
                            break;
                        }
                    }

                    btnEdit.Text = "修改成功";
                    btnEdit.Text = "修改";
                }
                else
                {
                    MessageBox.Show("识别结果不能为空");
                }
            }
            finally
            {
                btnEdit.Enabled = true;
            }
        }

        /// <summary>
        /// 推送数据给上位机业务系统
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReport_Click(object sender, EventArgs e)
        {
          //  btnReport.Text = "推送";
            //btnReport.Enabled = false;
            AutoCloseMessageBox.Show("推送中...");
            Task.Factory.StartNew(() =>
            {
                var service = ReportServiceFactory.getService();
                this.boxModel = this.boxModel == null ? new BoxModel() : boxModel;
                service.Report(new ReportDTO()
                {
                    BoxModel = this.boxModel,
                    OcrResults = FormDataBridge.OCRDataList
                });
               // btnReport.Text = "推送";
                //btnReport.Enabled = true;
            });
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            if (this.dataGridView.CurrentRow != null)
            {
                rowIndex = this.dataGridView.CurrentRow.Index;
            }

            if (rowIndex - 1 < 0)
            {
                return;
            }

            this.dataGridView.CurrentCell = this.dataGridView.Rows[rowIndex - 1].Cells[0];
            CurrentRowChanged(rowIndex - 1);
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            if (this.dataGridView.CurrentRow != null)
            {
                rowIndex = this.dataGridView.CurrentRow.Index;
            }
            if (rowIndex + 1 > this.dataGridView.Rows.Count - 1)
            {
                return;
            }
            this.dataGridView.CurrentCell = this.dataGridView.Rows[rowIndex + 1].Cells[0];
            CurrentRowChanged(rowIndex + 1);
        }

        private void dataGridView_Paint(object sender, PaintEventArgs e)
        {
            //定义边框矩形位置
            Rectangle rect = new Rectangle(0, 0, this.dataGridView.Width - 1, this.dataGridView.Height - 1);
            //定义画笔颜色
            Pen p = new Pen(Color.FromArgb(193, 193, 193));
            //或者选择颜色枚举Pen p = Pens.DarkGray;
            //画
            e.Graphics.DrawRectangle(p, rect);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (dataGridView.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (CameraHandler.CurrentBatchDir == null)
            {
                Console.WriteLine("还没有拍照过");
                return;
            }

            DateTime now = DateTime.Now;
            var fileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0')
                + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0') + ".csv";
            var fullPath = Path.Combine(CameraHandler.CurrentBatchDir, fileName);
            Stream stream = File.Create(fullPath);
            StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
            string strLine = "";
            var skipColumns = new int[] { 0 };
            try
            {
                //表头
                for (int i = 0; i < dataGridView.ColumnCount - 1; i++)
                {
                    if (skipColumns.Contains(i))
                    {
                        continue;
                    }
                    if (dataGridView.Columns[i].Visible)
                    {
                        strLine += dataGridView.Columns[i].HeaderText;
                        if (i > 0) strLine += ",";
                    }
                }
                strLine.Remove(strLine.Length - 1);
                sw.WriteLine(strLine);
                strLine = "";
                //表的内容
                for (int j = 0; j < dataGridView.Rows.Count; j++)
                {
                    strLine = "";//序号
                    int colCount = dataGridView.Columns.Count - 1;
                    for (int k = 0; k < colCount; k++)
                    {
                        if (skipColumns.Contains(k))
                        {
                            continue;
                        }
                        if (!dataGridView.Columns[k].Visible)
                        {
                            continue;
                        }
                        if (dataGridView.Rows[j].Cells[k].Value == null) strLine += "";
                        else
                        {
                            string cell = dataGridView.Rows[j].Cells[k].Value.ToString().Trim();
                            //防止里面含有特殊符号
                            cell = cell.Replace("\"", "\"\"");
                            cell = "\"" + cell + "\"";
                            strLine += cell;
                        }
                        if (k > 0 && k < colCount) strLine += ",";
                    }
                    sw.WriteLine(strLine);
                }
                sw.Close();
                stream.Close();
                MessageBox.Show("数据已经导出到：" + fullPath, "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                string filePath = CameraHandler.CurrentBatchDir;
                if (String.IsNullOrEmpty(filePath))
                {
                    MessageBox.Show("未找到任何文件夹，请先拍照");
                    return;
                }
                util.FileHelper.openDir(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void btnDataClear_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定清空吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result.Equals(DialogResult.Yes))
            {
                this.dataGridView.Rows.Clear();
                FormDataBridge.ClearData();
                this.resetRightArea();
                if (clearListDelegate != null) clearListDelegate.Invoke();

            }
        }

        private void resetRightArea()
        {
            //右侧
            if (straightenPictureBox.Image != null)
            {
                Graphics g = Graphics.FromImage(straightenPictureBox.Image);
                g.Clear(Color.White);
                g.Dispose();
                straightenPictureBox.Refresh();
            }

            if (previewPanel.BackgroundImage != null)
            {
                Graphics g = Graphics.FromImage(previewPanel.BackgroundImage);
                g.Clear(Color.White);
                g.Dispose();
                previewPanel.Refresh();
            }

            /* if (previewPictureBox.Image != null)
             {
                 Graphics g = Graphics.FromImage(previewPictureBox.Image);
                 g.Clear(Color.White);
                 g.Dispose();
                 straightenPictureBox.Refresh();
             }*/

            txtCode.Text = string.Empty;
        }

        private void btnRotate_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                var image = straightenPictureBox.Image;
                if (image == null) return;

                float dx = image.Width / 2.0f;
                float dy = image.Height / 2.0f;

                Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
                rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                Graphics g = Graphics.FromImage(rotatedBmp);
                g.TranslateTransform(dx, dy);
                g.RotateTransform(180);
                g.TranslateTransform(-dx, -dy);
                g.DrawImage(image, new PointF(0, 0));

                straightenPictureBox.Image = rotatedBmp;
                //image.Dispose();
                g.Dispose();
            });
        }

        /// <summary>
        /// 重新拉直
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReStraighten_Click(object sender, EventArgs e)
        {
            if (FormDataBridge.OCRDataList.Count<=0) {
                return;
            }
            OCRResult result = FormDataBridge.OCRDataList[currentRowIndex];
            if (result.status == 2)
            {
                return;
            }
            this.btnReStraighten.Text = "拉直中...";
            this.btnReStraighten.Enabled = false;
            //图片翻转90度
            string originalFilePath = result.filePath;
            string newFilePath = result.filePath.Replace(".jpg", "_90.jpg");
            RotateAndSaveImage(result.filePath, newFilePath);
            //File.Copy(newFilePath,originalFilePath,true);
            //File.Delete(newFilePath);
            result.filePath = newFilePath;
            result.errorMsg = "";

            ThreadHelper.ExcuteThreadTask(() =>
            {
                FormDataBridge.OCRReWork(result);
            }, 300);
        }

        /// <summary>
        /// 图片翻转90度
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        private void RotateAndSaveImage(String input, String output)
        {
            //create an object that we can use to examine an image file
            using (Image img = Image.FromFile(input))
            {
                //rotate the picture by 90 degrees and re-save the picture as a Jpeg
                img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                img.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }


        private void dataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine("dataGridView_KeyDown");
            int rowIndex = 0;
            if (this.dataGridView.CurrentRow != null)
            {
                rowIndex = this.dataGridView.CurrentRow.Index;
            }

            if (e.KeyCode == Keys.Down) //键盘按方向下
            {
                Console.WriteLine("RIGHT");
                if ((rowIndex + 1) <= this.dataGridView.RowCount - 1)
                {
                    CurrentRowChanged(rowIndex + 1);
                }
            }
            else if (e.KeyCode == Keys.Up)
            {
                //Console.WriteLine("LEFT");
                if (rowIndex - 1 >= 0)
                {
                    CurrentRowChanged(rowIndex - 1);
                }
            }
        }

        private void dataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            /* //显示在HeaderCell上
             for (int i = 0; i < this.dataGridView.Rows.Count; i++)
             {
                 DataGridViewRow r = this.dataGridView.Rows[i];
                 r.HeaderCell.Value = string.Format("{0}", i + 1);
             }
             this.dataGridView.Refresh();*/
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int selectedCount = 0;
            for (int i = 0; i < this.dataGridView.RowCount; i++)
            {
                var row = this.dataGridView.Rows[i];
                var rowChecked = (bool)((DataGridViewCheckBoxCell)row.Cells[0]).Value;
                if (rowChecked)
                {
                    selectedCount++;
                }
            }
            if (selectedCount<=0) {
                MessageBox.Show("请选择要删除的数据");
                return;
            }

            if (MessageBox.Show(String.Format("确定要删除这{0}条数据吗？", selectedCount),
                "删除提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                var anyFound = false;
                for (int i = 0; i < this.dataGridView.RowCount; i++)
                {
                    var row = this.dataGridView.Rows[i];
                    var rowChecked = (bool)((DataGridViewCheckBoxCell)row.Cells[0]).Value;
                    if (rowChecked)
                    {
                        anyFound = true;
                        dataGridView.Rows.RemoveAt(i);
                        FormDataBridge.removeAt(i);
                        i--;
                    }
                }
                this.resetRightArea();
                if (!anyFound)
                {
                    AutoCloseMessageBox.Show("请先选中要删除的数据");
                }
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLocation_Click(object sender, EventArgs e)
        {
            OCRResult result = FormDataBridge.OCRDataList[currentRowIndex];
            if (result.nail == null)
            {
                AutoCloseMessageBox.Show("只有自动识别的钉子才能定位到它的位置");
                return;
            }

            btnLocation.Enabled = false;
            btnLocation.Text = "移动中";
            try
            {
                FormDataBridge.odlImageOCrResult = result;
                var xyz = result.nail.actualXyz;
                CameraPreviewForm form = new CameraPreviewForm(xyz);
                form.ShowDialog();
                btnLocation.Enabled = true;
                btnLocation.Text = "定位到它";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void btnOCR_Click(object sender, EventArgs e)
        {
            if (FormDataBridge.OCRDataList.Count<=0) {
                return;
            }
            OCRResult result = FormDataBridge.OCRDataList[currentRowIndex];
            if (result.status == 3)
            {
                return;
            }
            this.btnRedo.Text = "处理中...";
            this.btnRedo.Enabled = false;
            result.errorMsg = "";

            ThreadHelper.ExcuteThreadTask(() =>
            {
                FormDataBridge.OCRRedo(result);
            }, 300);
        }

        private void orderCheckBtn_Click(object sender, EventArgs e)
        {
            OrderIndex orderIndex = new OrderIndex();
            orderIndex.Show();
        }
    }
}
